import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' if (dart.library.html) 'src/stub/path.dart' as path_helper;

Future<String> createDirectory() async {
  final Directory directory = await getApplicationDocumentsDirectory();

  var file = Directory("${directory.path}\\logs");
  try {
    bool exist = await file.exists();
    if (exist == false) {
      await file.create();
    }
  } catch(e) {
    print("createDirectory error");
  }
  // String path = path_helper.join(file.path, '${now.year}${now.month}${now.day}.txt',);
  // return path;
  return file.path;
}

class LoggerManager {
  //私有构造函数
  LoggerManager._internal();

  //保存单例
  static final LoggerManager _singleton = LoggerManager._internal();

  //工厂构造函数
  factory LoggerManager() => _singleton;

  IOSink? _sink;
  File? file;
  String? _currentDate;
  String? fileDir;

  getDirectoryForLogRecord()  {
    String currentDate = getCurrentDay();
    if (currentDate != _currentDate) {
      _currentDate = currentDate;
      file = File(path_helper.join(fileDir!,'$currentDate.txt'));
      _sink = file!.openWrite(mode: FileMode.writeOnlyAppend,);
    }

  }

  String getCurrentDay() {
    DateTime dateTime = DateTime.now();
    return "${dateTime.year}${dateTime.month}${dateTime.day}";
  }

  write(String title,String message) {
    _sink?.write("${DateTime.now().toString()}    $title   $message \r\n");
    getDirectoryForLogRecord();
  }

  initLogger() async {
    fileDir = await createDirectory();
    getDirectoryForLogRecord();
  }

  close() async {
    await _sink?.flush();
    await _sink?.close();
  }

}
